namespace FIREFLYX {
    /**
     * 文件加载
     */
    export class FileLoad {
        /** 网络加载失败后重试 */
        public static enableRetry: boolean = false;
        /** 加载失败后重试时间间隔 */
        public static retryInterval: number = 1000;
        public static xhr(url: string, rType: XMLHttpRequestResponseType): Promise<any> {
            return new Promise<any>((res, rej) => {
                let xhreq = new XMLHttpRequest();
                let success = false;
                xhreq.responseType = rType;
                xhreq.open("GET", url);
                xhreq.send();
                //event reg
                xhreq.onreadystatechange = () => {
                    if (xhreq.readyState == 4) {
                        switch (xhreq.status) {
                            case 200:
                                success = true;
                                res(xhreq.response);
                                break;
                            case 404: rej(new Error(`got a 404: ${url}`)); break;
                            default:
                        }
                    }
                };
                xhreq.onloadend = () => {
                    if (success) return;
                    if (!this.enableRetry) {
                        rej(new Error(`load fial: ${url}`));
                        return;
                    }
                    //加载失败 重试
                    console.log("加载失败 重试");
                };
                xhreq.onerror = (ev) => {
                    rej(new Error(`load error : ${url}`));
                };
            });
        }

        /**
         * 加载image 资源
         * @param uri 资源路径
         * @returns 
         */
        public static loadImage(uri: string) {
            let imgP = new Promise<HTMLImageElement>((res, rej) => {
                let img = new Image();
                img.src = uri;
                img.onload = () => { res(img); };
                img.onerror = (err) => { rej(err); };
            });

            return imgP;
        }
    }
}